const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://127.0.0.1:5000';

async function client(endpoint, { body, ...customConfig } = {}) {
  const headers = { 'Content-Type': 'application/json' };
  
  const config = {
    method: body ? 'POST' : 'GET',
    ...customConfig,
    headers: {
      ...headers,
      ...customConfig.headers,
    },
    // 移除 credentials
  };

  if (body) {
    config.body = JSON.stringify(body);
  }

  try {
    // 使用相对路径
    const response = await fetch(`${endpoint}`, config);
    
    // 处理响应内容
    const data = await response.json();
    
    if (!response.ok) {
      throw new Error(data.message || `请求失败: ${response.status}`);
    }
    
    return data;
  } catch (error) {
    console.error(`API请求错误 [${endpoint}]:`, error);
    throw error;
  }
}

// 定义API方法
const API = {
  createDataSource: (data) => client('/api/data-sources', { body: data }).then(res => res.data),
  getDataSourceTypes: () => client('/api/data-sources/types').then(res => res.data),
  getDataSources: () => client('/api/data-sources').then(res => res.data),
  getTaskResults: (taskId) => client(`/api/profile/results/${taskId}`).then(res => res.data),
  getERModels: () => client('/api/er-models').then(res => res.data),
  getTasks: () => client('/api/dashboard/task_list').then(res => res.data),
  pollTaskStatus: (taskId) => client(`/api/profile/status/${taskId}`).then(res => res.data),
  // 获取任务摘要统计
  getTaskStats: () => client('/api/profile/task-stats').then(res => res.data),
  // 获取数据库任务分布
  getDbDistribution: () => client('/api/profile/db-distribution').then(res => res.data),
  startTask: (taskId) => client('/api/profile/start', {
    method: 'POST',
    body: { task_id: taskId }  // 只传递任务ID
  }).then(res => res.data), 

  createERModel: async (data) => {
    // 准备基本参数
    const baseParams = {
      source_id: data.source_id,
      name: data.name,
      config_type: data.config_type,
      scope: data.scope || 'private'
    };
  
    // 处理文件类型
    if (data.config_type === 'er_file') {
      // 确保content字段存在
      if (!data.content) {
        throw new Error('ER文件类型必须提供content字段');
      }
      
      // 直接使用已传递的content
      return client('/api/er-models', {
        method: 'POST',
        body: {
          ...baseParams,
          content: data.content, // 使用已传递的内容
          file_name: data.file_name || '未命名文件'
        }
      }).then(res => res.data);
    } 
    
    // 处理表名类型
    return client('/api/er-models', {
      method: 'POST',
      body: {
        ...baseParams,
        table_name: data.table_name
      }
    }).then(res => res.data);
  }
};


export default API;